<template>
  <div class="login-page">
    <div class="container">
      <div class="login-container">
        <div class="form-container">
          <h1 class="page-title">登录</h1>
          
          <el-form 
            ref="loginForm" 
            :model="loginForm" 
            :rules="rules" 
            label-position="top"
            @submit.prevent="onSubmit"
          >
            <el-form-item label="用户名" prop="username">
              <el-input 
                v-model="loginForm.username" 
                placeholder="请输入用户名"
                prefix-icon="el-icon-user"
              />
            </el-form-item>
            
            <el-form-item label="密码" prop="password">
              <el-input 
                v-model="loginForm.password" 
                type="password" 
                placeholder="请输入密码"
                prefix-icon="el-icon-lock"
                show-password
              />
            </el-form-item>
            
            <div class="form-actions">
              <el-button 
                type="primary" 
                :loading="loading" 
                @click="onSubmit"
                class="submit-btn"
              >
                登录
              </el-button>
            </div>
          </el-form>
          
          <div class="form-footer">
            <p>还没有账号? <router-link to="/register">立即注册</router-link></p>
          </div>
        </div>
        
        <div class="image-container">
          <div class="image-overlay">
            <h2>欢迎回来</h2>
            <p>登录您的账户，开始领养之旅</p>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { mapActions, mapGetters } from 'vuex';
import { ElMessage } from 'element-plus';
import axios from 'axios';

export default {
  name: 'Login',
  data() {
    return {
      loginForm: {
        username: '',
        password: ''
      },
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, message: '密码长度不能小于6个字符', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    ...mapGetters({
      loading: 'isLoading',
      error: 'error',
      token: 'auth/token',
      isAuthenticated: 'auth/isAuthenticated',
      currentUser: 'auth/currentUser'
    })
  },
  methods: {
    ...mapActions({
      login: 'auth/login',
      setError: 'setError'
    }),
    
    // 验证令牌是否成功存储
    verifyTokenStorage() {
      // 从localStorage获取token
      const storedToken = localStorage.getItem('token');
      const storedUser = localStorage.getItem('user');
      
      console.log('验证令牌状态 - localStorage token:', !!storedToken);
      console.log('验证令牌状态 - localStorage user:', !!storedUser);
      console.log('验证令牌状态 - Vuex token:', !!this.token);
      console.log('验证令牌状态 - Vuex isAuthenticated:', this.isAuthenticated);
      
      if (!storedToken) {
        console.error('令牌未成功存储到localStorage');
        return false;
      }
      
      if (!this.token) {
        console.error('令牌未成功存储到Vuex');
        return false;
      }
      
      return true;
    },
    
    // 设置请求拦截器
    setupAxiosInterceptor() {
      const token = localStorage.getItem('token');
      if (!token) {
        console.error('无法设置拦截器，令牌不存在');
        return;
      }
      
      console.log('手动设置Axios拦截器');
      
      // 添加请求拦截器
      axios.interceptors.request.use(config => {
        // 从localStorage获取令牌
        const currentToken = localStorage.getItem('token');
        if (currentToken) {
          // 添加认证头
          config.headers['Authorization'] = `Bearer ${currentToken}`;
          config.headers['x-auth-token'] = currentToken;
        }
        return config;
      });
    },
    
    async onSubmit() {
      try {
        // 清除先前的令牌和用户数据
        localStorage.removeItem('token');
        localStorage.removeItem('user');
        
        // 验证表单
        await this.$refs.loginForm.validate();
        
        console.log('开始登录请求...', {
          username: this.loginForm.username,
          passwordLength: this.loginForm.password ? this.loginForm.password.length : 0
        });
        
        // 设置超时，确保登录不会无限等待
        const loginPromise = this.login(this.loginForm);
        const timeoutPromise = new Promise((_, reject) => 
          setTimeout(() => reject(new Error('登录请求超时')), 15000)
        );
        
        // 使用Promise.race确保请求不会超时
        const success = await Promise.race([loginPromise, timeoutPromise]);
        
        if (success) {
          console.log('登录请求成功，验证令牌和用户信息...');
          
          // 验证令牌是否正确存储
          const tokenValid = this.verifyTokenStorage();
          if (!tokenValid) {
            ElMessage.error('登录后令牌保存失败，请重试');
            return;
          }
          
          // 验证用户信息是否获取到
          if (!this.currentUser || !this.currentUser.username) {
            console.error('登录成功但用户信息不完整:', this.currentUser);
            ElMessage.warning('登录成功但获取用户信息失败，将为您重新登录');
            
            // 尝试重新登录一次
            const retrySuccess = await this.login(this.loginForm);
            if (!retrySuccess || !this.currentUser) {
              ElMessage.error('登录失败，无法获取用户信息');
              return;
            }
          }
          
          // 设置请求拦截器
          this.setupAxiosInterceptor();
          
          // 从查询参数获取重定向路径
          const redirectPath = this.$route.query.redirect || '/';
          console.log('准备重定向到:', redirectPath);
          
          // 延迟一下再跳转，确保令牌已保存
          setTimeout(() => {
            // 再次验证重定向前的认证状态
            if (this.isAuthenticated && this.currentUser) {
              console.log('认证有效，正在跳转...');
              this.$router.push(redirectPath);
              
              ElMessage({
                message: `欢迎回来，${this.currentUser.username}！`,
                type: 'success'
              });
            } else {
              console.error('重定向前认证状态无效');
              ElMessage.error('登录状态异常，请重新登录');
            }
          }, 1000);
        } else {
          console.error('登录失败，未返回成功状态');
          ElMessage.error('登录失败，请检查用户名和密码');
        }
      } catch (error) {
        // 表单验证失败或其他错误
        console.error('登录过程中发生错误:', error);
        ElMessage.error('登录失败: ' + (error.message || '未知错误'));
      }
    }
  },
  // 在组件销毁前清除错误信息
  beforeUnmount() {
    if (this.error) {
      this.setError(null);
    }
  },
  mounted() {
    // 检查是否已经有有效令牌
    if (this.isAuthenticated && this.currentUser) {
      console.log('用户已登录，重定向到首页');
      this.$router.push('/');
    }
  }
}
</script>

<style lang="scss" scoped>
.login-page {
  min-height: calc(100vh - 200px);
  display: flex;
  align-items: center;
  padding: 40px 0;
}

.login-container {
  background-color: white;
  border-radius: 10px;
  box-shadow: 0 0 20px rgba(0, 0, 0, 0.1);
  display: flex;
  overflow: hidden;
  min-height: 500px;
}

.form-container {
  flex: 1;
  padding: 40px;
  display: flex;
  flex-direction: column;
}

.image-container {
  flex: 1;
  background-image: url('https://images.unsplash.com/photo-1560807707-8cc77767d783?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=675&q=80');
  background-size: cover;
  background-position: center;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  
  &::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.4);
  }
}

.image-overlay {
  position: relative;
  color: white;
  text-align: center;
  padding: 20px;
  
  h2 {
    font-size: 2rem;
    margin-bottom: 10px;
  }
  
  p {
    font-size: 1.2rem;
  }
}

.form-actions {
  margin-top: 20px;
}

.submit-btn {
  width: 100%;
}

.form-footer {
  margin-top: 20px;
  text-align: center;
  
  a {
    color: var(--primary-color);
    font-weight: bold;
  }
}

@media (max-width: 768px) {
  .login-container {
    flex-direction: column-reverse;
  }
  
  .image-container {
    height: 200px;
  }
}
</style> 